/**
 * 输入处理系统 - 管理键盘和鼠标输入
 */
class InputHandler {
    constructor() {
        this.keys = {};
        this.mouse = {
            position: new Vector2D(0, 0),
            buttons: {},
            wheel: 0
        };
        
        this.setupEventListeners();
        this.keyMappings = this.createKeyMappings();
    }

    createKeyMappings() {
        return {
            // 移动控制
            moveUp: ['KeyW', 'ArrowUp'],
            moveDown: ['KeyS', 'ArrowDown'],
            moveLeft: ['KeyA', 'ArrowLeft'],
            moveRight: ['KeyD', 'ArrowRight'],
            
            // 游戏控制
            shoot: ['Space'],
            missile: ['KeyM'], // 导弹发射
            pause: ['Escape', 'KeyP'],
            restart: ['KeyR'],
            
            // 菜单控制
            select: ['Enter'],
            back: ['Escape'],
            
            // 调试控制
            debug: ['KeyF'],
            toggleFullscreen: ['KeyF11']
        };
    }

    setupEventListeners() {
        // 键盘事件
        window.addEventListener('keydown', (e) => this.onKeyDown(e));
        window.addEventListener('keyup', (e) => this.onKeyUp(e));
        
        // 鼠标事件
        window.addEventListener('mousedown', (e) => this.onMouseDown(e));
        window.addEventListener('mouseup', (e) => this.onMouseUp(e));
        window.addEventListener('mousemove', (e) => this.onMouseMove(e));
        window.addEventListener('wheel', (e) => this.onMouseWheel(e));
        
        // 触摸事件（移动端支持）
        window.addEventListener('touchstart', (e) => this.onTouchStart(e));
        window.addEventListener('touchend', (e) => this.onTouchEnd(e));
        window.addEventListener('touchmove', (e) => this.onTouchMove(e));
        
        // 防止右键菜单
        window.addEventListener('contextmenu', (e) => e.preventDefault());
        
        // 防止页面滚动
        window.addEventListener('keydown', (e) => {
            if (['Space', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(e.code)) {
                e.preventDefault();
            }
        });
    }

    onKeyDown(event) {
        this.keys[event.code] = true;
        
        // 阻止默认行为
        if (this.isGameKey(event.code)) {
            event.preventDefault();
        }
    }

    onKeyUp(event) {
        this.keys[event.code] = false;
        
        if (this.isGameKey(event.code)) {
            event.preventDefault();
        }
    }

    onMouseDown(event) {
        this.mouse.buttons[event.button] = true;
        event.preventDefault();
    }

    onMouseUp(event) {
        this.mouse.buttons[event.button] = false;
        event.preventDefault();
    }

    onMouseMove(event) {
        const rect = event.target.getBoundingClientRect();
        this.mouse.position.set(
            event.clientX - rect.left,
            event.clientY - rect.top
        );
    }

    onMouseWheel(event) {
        this.mouse.wheel = event.deltaY;
        event.preventDefault();
    }

    onTouchStart(event) {
        if (event.touches.length > 0) {
            const touch = event.touches[0];
            const rect = event.target.getBoundingClientRect();
            this.mouse.position.set(
                touch.clientX - rect.left,
                touch.clientY - rect.top
            );
            this.mouse.buttons[0] = true;
        }
        event.preventDefault();
    }

    onTouchEnd(event) {
        this.mouse.buttons[0] = false;
        event.preventDefault();
    }

    onTouchMove(event) {
        if (event.touches.length > 0) {
            const touch = event.touches[0];
            const rect = event.target.getBoundingClientRect();
            this.mouse.position.set(
                touch.clientX - rect.left,
                touch.clientY - rect.top
            );
        }
        event.preventDefault();
    }

    // 检查是否按下某个键
    isKeyPressed(keyCode) {
        return this.keys[keyCode] || false;
    }

    // 检查是否按下某个动作对应的键
    isActionPressed(action) {
        const keyCodes = this.keyMappings[action];
        if (!keyCodes) return false;
        
        return keyCodes.some(keyCode => this.isKeyPressed(keyCode));
    }

    // 检查鼠标按钮状态
    isMousePressed(button = 0) {
        return this.mouse.buttons[button] || false;
    }

    // 获取鼠标位置
    getMousePosition() {
        return this.mouse.position.clone();
    }

    // 获取鼠标滚轮状态
    getMouseWheel() {
        const wheel = this.mouse.wheel;
        this.mouse.wheel = 0; // 重置滚轮状态
        return wheel;
    }

    // 获取移动向量
    getMovementVector() {
        const movement = new Vector2D(0, 0);
        
        if (this.isActionPressed('moveLeft')) movement.x -= 1;
        if (this.isActionPressed('moveRight')) movement.x += 1;
        if (this.isActionPressed('moveUp')) movement.y -= 1;
        if (this.isActionPressed('moveDown')) movement.y += 1;
        
        // 标准化对角线移动
        if (movement.magnitude() > 0) {
            movement.normalize();
        }
        
        return movement;
    }

    // 检查是否为游戏相关按键
    isGameKey(keyCode) {
        const allKeys = Object.values(this.keyMappings).flat();
        return allKeys.includes(keyCode);
    }

    // 重置所有输入状态
    reset() {
        this.keys = {};
        this.mouse.buttons = {};
        this.mouse.wheel = 0;
    }

    // 设置自定义键位映射
    setKeyMapping(action, keyCodes) {
        if (Array.isArray(keyCodes)) {
            this.keyMappings[action] = keyCodes;
        } else {
            this.keyMappings[action] = [keyCodes];
        }
    }

    // 获取当前按下的所有键
    getPressedKeys() {
        return Object.keys(this.keys).filter(key => this.keys[key]);
    }

    // 检查组合键
    isComboPressed(keys) {
        return keys.every(key => this.isKeyPressed(key));
    }

    // 振动反馈（如果支持）
    vibrate(pattern = [100]) {
        if (navigator.vibrate) {
            navigator.vibrate(pattern);
        }
    }

    // 全屏切换
    toggleFullscreen() {
        if (!document.fullscreenElement) {
            document.documentElement.requestFullscreen().catch(console.warn);
        } else {
            document.exitFullscreen().catch(console.warn);
        }
    }

    // 更新输入状态（每帧调用）
    update() {
        // 处理特殊按键
        if (this.isActionPressed('toggleFullscreen')) {
            this.toggleFullscreen();
        }
        
        // 重置一次性事件
        this.mouse.wheel = 0;
    }

    // 销毁输入处理器
    destroy() {
        window.removeEventListener('keydown', this.onKeyDown);
        window.removeEventListener('keyup', this.onKeyUp);
        window.removeEventListener('mousedown', this.onMouseDown);
        window.removeEventListener('mouseup', this.onMouseUp);
        window.removeEventListener('mousemove', this.onMouseMove);
        window.removeEventListener('wheel', this.onMouseWheel);
        window.removeEventListener('touchstart', this.onTouchStart);
        window.removeEventListener('touchend', this.onTouchEnd);
        window.removeEventListener('touchmove', this.onTouchMove);
        window.removeEventListener('contextmenu', (e) => e.preventDefault());
    }
} 